﻿using System;
using SS.Common.Threading;

namespace SS.WPF.Framework.Coroutines
{
    public class LongRunResult: ResultBase
    {
        #region Fields

        /// <summary>
        /// The exception is occurred while excuting
        /// </summary>
        private Exception _exception;

        #endregion

        #region Methods

        protected override void DoExecute()
        {
            // Start LoadScreen
            if (this._beforeAction != null)
            {
                this._beforeAction();
            }

            // Stat async action
            ExecuteEx.OnBackgroundThread(this.ExecuteBackgroundAction, this.ExecuteBackgroundActionCallback);
        }

        /// <summary>
        /// Execute background action
        /// </summary>
        private void ExecuteBackgroundAction()
        {
            try
            {
                if (this._doAction != null)
                {
                    this._doAction();
                }
            }
            catch (Exception ex)
            {
                this._exception = ex;
            }
        }

        /// <summary>
        /// Execute background action callback
        /// </summary>
        private void ExecuteBackgroundActionCallback()
        {
            // Remove backgroundaction indicator
            if (this._unRegistryBackgroundAction != null)
            {
                this._unRegistryBackgroundAction();
            }

            // Stop LoadScreen
            if (this._afterAction != null)
            {
                try
                {
                    this._afterAction();
                }
                catch (Exception ex)
                {
                    this.HandleException(ex);
                }
            }

            // No exception
            if (this._exception == null)
            {
                if (this._callbackAction != null)
                {
                    try
                    {
                        this._callbackAction();
                    }
                    catch (Exception ex)
                    {
                        this.HandleException(ex);
                    }
                }
            }
            else
            {
                // Handle exception
                this.HandleException(this._exception);
                if (!this._continuousOnException)
                {
                    return;
                }
            }

            this.OnCompleted(this, null);
        }

        /// <summary>
        /// The this as actual instance
        /// </summary>
        /// <returns>
        /// The LongRunResult instance
        /// </returns>
        protected override IFluentResult GetActualResultInstance()
        {
            return this;
        }

        #endregion
    }
}
